package com.situ.car.dao.Impl;

import com.situ.car.dao.IUserDao;
import com.situ.car.pojo.entity.Admin;
import com.situ.car.pojo.entity.User;
import com.situ.car.pojo.query.UserQuery;
import com.situ.car.util.JDBCUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements IUserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public User login(String account, String password) {
        try {
            return template.queryForObject("select id, username, account, password, avatar, status from user where account=? and password=?",
                    new BeanPropertyRowMapper<>(User.class), account, password);
        } catch (EmptyResultDataAccessException ex) {
            return null;
        }
    }
    @Override
    public User selectByInfoId(Integer id) {
        return template.queryForObject("SELECT * FROM user where id=?", new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public int updateInfo(User user) {
        try {
            return template.update("update user set username=?, account=?, avatar=?, gender=?, age=?, email=?, phone=? where id=?",user.getUsername(), user.getAccount(), user.getAvatar(), user.getGender(), user.getAge(), user.getEmail(), user.getPhone(), user.getId());
        } catch (DuplicateKeyException e) {
            return 0;
        }
    }

    @Override
    public User selectAccount(Integer id) {
        return template.queryForObject("SELECT id,account FROM user where id=?", new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public User selectPassword(Integer id) {
        return template.queryForObject("SELECT password FROM user where id=?", new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public void updatePassword(Integer id, String newPassword) {
        template.update("update user set password=? where id=?", newPassword, id);
    }

    @Override
    public Integer selectByAccount(User user) {
        return template.queryForObject("select count(*) from user where account=?", Integer.class,user.getAccount());
    }

    @Override
    public void register(User user) {
        template.update("insert into user (username, account, password, phone) VALUES (?,?,?,?)",
                user.getUsername(), user.getAccount(), user.getPassword(), user.getPhone());
    }
}
